package com.angel.util;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.angel.activity.LoginActivity;
import com.angel.activity.QuitProgress;
import com.angel.entity.Task;
import com.angel.service.TaskService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.widget.TextView;
import android.widget.Toast;

/*工具类，常用的全局方法*/
public class BaseUtil extends Activity {
	/*设置中文字体为粗体*/
	public static void setBoldText(TextView textView){
		textView.getPaint().setFakeBoldText(true);
	}
	/*获取json值*/
	public static String getValueFromJSON(String param){
		 String isSucess="";
		 JSONObject jsonObject=null;
		 try {
			 jsonObject=new JSONObject(param);
			 isSucess=jsonObject.getString("isSuccess");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		 return isSucess;
	}
	/*将json数据通过数据转换为实体*/
	public static Object getEntityFromJson(String json,Type type){
		Object obj=null;
		Gson gson=new Gson();
		obj=gson.fromJson(json, type);
		return obj;
	}
	
	  /*缩放图片大小，适应屏幕*/
//    public static Drawable ShrinkDrawable(Drawable dr,int w,int h){
//    	Bitmap bitmap=drawableToBitmap(dr);
//    	//获取图片大小
//    	int picWidth=bitmap.getWidth();
//    	int picHeight=bitmap.getHeight();
    	
//    	Matrix matrix=new Matrix();
//    	float sx=(float)(screenWidth-30)/picWidth;
//    	float sy=(float)250/picHeight;
    	
//    	matrix.postScale(sx, sy);
//    	//static Bitmap 	createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter)
//    	bitmap=Bitmap.createBitmap(bitmap,0,0,picWidth,picHeight,matrix,true);
////    	bitmap=bitmap.createScaledBitmap(bitmap, screenWidth-30, 200, true);
//    	return new BitmapDrawable(bitmap);
//    }
	
	/*@map为传递封装的数据
	 * 启动service*/
    public static void startService(int taskId,Activity activity,HashMap<String,String> map){
		Intent intentService=new Intent(activity,TaskService.class);
        activity.startService(intentService);
        Task task=new Task(taskId,map);
		TaskService.newTask(task);
		TaskService.addActivity(activity);
    }
    /*全局方法显示Toast内容，text为要显示的内容*/
    public static void makeToast(Activity activity,String text){
    	Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
    }
    /*全局方法显示Toast内容，context参数为上下文*/
    public static void makeToast(Context context,String text){
    	Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }
    /*显示退出对话框*/
    public static void showExitDialog(final Activity activity){
    	final QuitProgress quitProgress=new QuitProgress(activity);
    	AlertDialog.Builder builder=new AlertDialog.Builder(activity);
    	builder.setMessage("是否退出")
              .setCancelable(false)
    	 		.setPositiveButton("确定", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					quitProgress.exit();
					Intent intent=new Intent(activity,TaskService.class);
					activity.stopService(intent);//关闭services
					android.os.Process.killProcess(android.os.Process.myPid());
					android.os.Process.killProcess(android.os.Process.myTid());
					android.os.Process.killProcess(android.os.Process.myUid());
				}
            	  
              }).setNegativeButton("取消", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();//关闭对话框
				}
            	  
              });    
    	/*创建显示对话框*/
    	AlertDialog dialog=builder.create();
    	dialog.show();
    }
    /*退出当前账号*/
    public static void showChangeDialog(final Activity activity,final Context context){
    	
    	final QuitProgress quitProgress=new QuitProgress(activity);
    	AlertDialog.Builder builder=new AlertDialog.Builder(activity);
    	 builder.setMessage("是否退出当前账号")
                .setCancelable(false)
    	 		.setPositiveButton("确定", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					UserInfoUtil.clearUserMsg(context);
					quitProgress.changeAccount();
					Intent intent=new Intent(activity,TaskService.class);
					activity.stopService(intent);//关闭services
					android.os.Process.killProcess(android.os.Process.myPid());
					android.os.Process.killProcess(android.os.Process.myTid());
					android.os.Process.killProcess(android.os.Process.myUid());
				}
            	  
              }).setNegativeButton("取消", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();//关闭对话框
				}
            	  
              });    
    	/*创建显示对话框*/
    	AlertDialog dialog=builder.create();
    	dialog.show();
    }
    /*根据Uri查询获得真实存储路径*/
    public static String getUrlByUri(Uri uri,Activity activity){
    	String[] data={MediaStore.Images.Media.DATA};
    	Cursor cursor=activity.managedQuery(uri, data, null, null, null);
    	int index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    	cursor.moveToFirst();
    	String url=cursor.getString(index);
    	return url;
    }
    /*获取系统时间*/
	 public static long getTime(){
//		 Date date=new Date();
//		 SimpleDateFormat from=new SimpleDateFormat("yyyyMMddhhmmss");
//		 String time=from.format(date);
		     long time= System.currentTimeMillis();
		    return time;
	 }
	/*检查手机号是否绑定,若存在，则返回true */
	public static boolean isBindPhone(Context context){
			String phoneNum=UserInfoUtil.getValue(context, "phoneAccount","");
			if(phoneNum.equals("")){
				return false;
			}else{
				return true;
			}
	}
	


	/**获取屏幕分辨率
	 * @param activity
	 * @return 存储分辨率的对象
	 */
	public  static DisplayMetrics getResolutionRatio(Activity activity){
		DisplayMetrics dm=new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		return dm;
	}
	
	/**返回设备dip类型
	 * @param activity  当前activity对象
	 * @return ConstUtil.MDPI 中等分辨率 ConstUtil.HDPI 高分辨率 ConstUtil.XHDPI特高分辨率
	 */
	public static Integer getDpiType(Activity activity){
		DisplayMetrics dm=getResolutionRatio(activity);
		float dentity=dm.density;
		System.out.println("dentity is:"+dentity);
		if((0.75<=dentity)&&(dentity<=1.2)){
			return ConstUtil.MDPI;
		}else if(1.2<dentity&&dentity<=1.7){
			return ConstUtil.HDPI;
		}else if(1.7<dentity){
			return ConstUtil.XHDPI;
		}else if(dentity<0.75){
			return ConstUtil.MDPI;
		}
		return ConstUtil.MDPI;
	}
	
	/**
	 * @param context 上下文
	 * @param picName
	 * @return 返回获取的图片确切地址
	 */
	public static String getPicUrl(Context context,String picName){
		int dpiType=UserInfoUtil.getValue(context, "DpiType", 1);
		String picUrl="";
		switch(dpiType){
		case 1:
//			picUrl=HttpUtil.picUrl+"angel/mdpi/"+picName;
			picUrl=HttpUtil.picUrl+"uploadphoneImagesMdip/"+picName;
			break;
		case 2:
//			picUrl=HttpUtil.picUrl+"angel/hdpi/"+picName;
			picUrl=HttpUtil.picUrl+"uploadphoneImagesHdip/"+picName;
			break;
		case 3:
//			picUrl=HttpUtil.picUrl+"angel/xhdpi/"+picName;
			picUrl=HttpUtil.picUrl+"uploadphoneImagesXhdip/"+picName;
			break;
		default:
//			picUrl=HttpUtil.picUrl+"angel/hdpi/"+picName;
			picUrl=HttpUtil.picUrl+"uploadphoneImagesMdip/"+picName;
				break;
		}
		return picUrl;
	}
}
